package servlet.useraction;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.IServiceManager;
import service.exception.ServiceException;

import bean.LoginCredential;
import business.user.UserAuthentication;

public class LoginAction extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2958654408940724657L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		String errorMsg=null;
		if (session.getAttribute("register_done")!=null) {
			session.removeAttribute("register_done");
		}
		if (session.getAttribute("login_error")!=null) {
			session.removeAttribute("login_error");
		}
		LoginCredential lc = new LoginCredential();
		
		if (request.getParameter("accountfield")==null||request.getParameter("accountfield")=="") {
			errorMsg="Please fill in 'Account' field";
			session.setAttribute("login_error", errorMsg);
			response.sendRedirect("newlogin.jsp");
			return;
		}else {
			lc.setUsername(request.getParameter("accountfield"));
		}
		
		if (request.getParameter("passwordfield")==null||request.getParameter("passwordfield")=="") {
			errorMsg="Please fill in 'Password' field";
			session.setAttribute("login_error", errorMsg);
			response.sendRedirect("newlogin.jsp");
			return;
		}else {
			lc.setPassword(request.getParameter("passwordfield"));
		}
		
		//System.out.println(lc.getUsername());
		//System.out.println(lc.getPassword());

		IServiceManager serviceMgn = new UserAuthentication(request);
		try {
			if (serviceMgn.execute(UserAuthentication.SERVICE_LOGIN, lc)==null) {
				//System.out.println("login null");
				errorMsg="The account and password cannot be varified";
				session.setAttribute("login_error", errorMsg);
				response.sendRedirect("newlogin.jsp");
				return;
			}else {
				//System.out.println("login unnull");
				session.setAttribute("accountinfo", lc);
				response.sendRedirect("index.jsp");
			}			
			
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			errorMsg="Unknown error";
			session.setAttribute("login_error", errorMsg);
			response.sendRedirect("newlogin.jsp");
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
            doGet(request, response);
	}
}
